package com.soriya.nestlive.net

import android.content.Context
import android.util.Log
import com.google.gson.GsonBuilder
import com.soriya.nestlive.application.MyApplication
import com.soriya.nestlive.constant.CommonConstant
import com.soriya.nestlive.constant.ServerConstant
import com.soriya.nestlive.model.ResponseResult
import com.soriya.nestlive.util.ToastUtil
import okhttp3.OkHttpClient
import okhttp3.Protocol
import okhttp3.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.nio.charset.StandardCharsets
import java.util.concurrent.TimeUnit

object RetrofitClient {

    private val instance: Retrofit by lazy {
        Retrofit.Builder()
            .baseUrl(ServerConstant.SERVER_URL)
            .client(
                OkHttpClient.Builder()
                    .addInterceptor {
                        val sharedPreferences = MyApplication.instance.getSharedPreferences(
                            CommonConstant.USER_INFO_KEY,
                            Context.MODE_PRIVATE
                        )

                        val token = sharedPreferences.getString("token", null)

                        val request = it.request().newBuilder()
                            .let { builder ->
                                if (token != null)
                                    builder.addHeader("token", token)
                                else
                                    builder
                            }
                            .build()
                        val response = try {
                            it.proceed(request)
                        } catch (e: Exception) {
                            Log.i("SoRiya", "网络错误: ${e.message} | ${request.url}")
                            e.printStackTrace()
                            ToastUtil.show(MyApplication.instance, "网络错误")
                            throw e
                        }

                        if (request.url.encodedPath.startsWith("/api")) {
                            val source = response.body?.source()
                            source?.request(Long.MAX_VALUE)
                            val buffer = source?.buffer
                            val res = buffer?.clone()?.readString(StandardCharsets.UTF_8)

                            try {
                                val resJson =
                                    GsonBuilder().create().fromJson(res, ResponseResult.Success::class.java)

                                if (resJson.code != 200) {
                                    ToastUtil.show(MyApplication.instance, resJson.message)
                                }
                            } catch (e: Exception) {
                                e.printStackTrace()
                                ToastUtil.show(MyApplication.instance, "未知错误")
                            }
                        }

                        response
                    }
                    .connectTimeout(5, TimeUnit.SECONDS)
                    .build()
            )
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }

    val categoryApi: CategoryApi by lazy {
        instance.create(CategoryApi::class.java)
    }

    val channelApi: ChannelApi by lazy {
        instance.create(ChannelApi::class.java)
    }

    val liveApi: LiveApi by lazy {
        instance.create(LiveApi::class.java)
    }

    val userApi: UserApi by lazy {
        instance.create(UserApi::class.java)
    }

    val videoApi: VideoApi by lazy {
        instance.create(VideoApi::class.java)
    }

    val uploadApi: UploadApi by lazy {
        instance.create(UploadApi::class.java)
    }

}